import type { Column } from 'element-plus'
import Papa from 'papaparse'

import * as XLSX from 'xlsx'

export function genColumns(sample: Record<string, any>): Column<any>[] {
  return Object.keys(sample).map(key => ({
    key,
    dataKey: key,
    title: key,
    width: 120,
  }))
}

export function toCSV(json: any) {
  const csv = Papa.unparse(json)
  // 创建一个 Blob 对象
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'data.csv'
  a.click()
  URL.revokeObjectURL(url)
}

export function toXLS(json: any) {
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(json)
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, 'data.xls')
}

export function toXLSX(json: any) {
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(json)
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, 'data.xlsx')
}
